package com.radar.task.qh.雷音707;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.google.gson.Gson;
import com.radar.algorithm.MathCommon;
import com.radar.common.*;
import com.radar.io.RadarGridData;
import com.radar.io.radar346.Product382改;
import com.radar.license.LicenseVerify;
import com.radar.task.cd.Constants;
import com.radar.task.qh.ForecastTask;
import com.radar.visualize.PolarMap;
import com.radar.visualize.RasterMap;
import com.radar.visualize.ThematicMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.filefilter.RegexFileFilter;
import org.meteoinfo.global.PointD;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
@Service(value = "Product382ATask")
public class Product382A新Task {

    @Autowired
    private LicenseVerify licenseVerify;

    @Scheduled(fixedRate = 30 * 1000)
//    @Scheduled(fixedDelay = 1000)
    public void read346Product() {
//        if (!licenseVerify.verify()) {
//            licenseVerify.installLicense();
//            return;
//        }

        long time = System.currentTimeMillis();
        String[] prds = Constants.rootPath.split(";");
        List<File> files = new ArrayList<>();
        for (String prdinfo : prds) {
            if (FileUtil.isDirectory(prdinfo)) {
                files.addAll(FileUtil.loopFiles(prdinfo, new RegexFileFilter("^(\\d{8})_(\\d{6}).(.*?).bz2$")).stream().sorted(Comparator.comparingLong(i -> Long.parseLong(i.getName().substring(0, 15).replace("_", "")))).collect(Collectors.toList()));
            }
        }
        for (File file : files) {
            String next = file.getName();
            if (FileUtil.exist(file.getAbsolutePath() + ".PRODUCT_OK")) {
                continue;
            } else {
                FileUtil.touch(file.getAbsolutePath() + ".PRODUCT_OK");
            }
            try {
                log.info("start parse pre radar 362 product file : {} ", next);
                parse346(file);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("parse radar error file : {}", next);
            }
        }
        log.info("sum time : {}", System.currentTimeMillis() - time);
    }

    public void parse346(File file) throws Exception {
//        if (!file.getName().contains("20240109_193336")) {
//            return;
//        }
        String output = Constants.ncPath + File.separator + "346" + File.separator;
        String date = file.getName().substring(0, 15).replace("_", "");
//        String type = file.getName().substring(file.getName().length() - 3, file.getName().length());
        Product382改 product346 = new Product382改();
        ProductType type = product346.parseProduct(file.getAbsolutePath());
        RasterMap rasterMap = new RasterMap(null);
        BufferedImage bufferedImage = null;
        RadarGridData project = null;
        // 径向数据
        if (type == ProductType.ARD || type == ProductType.RVD) {
            // 方位涡度， 采用速度图例 , 数据 * 100, 单位 E-2/S
            // 径向散度， 采用速度图例 , 数据 * 10, 单位 E-3/S
            bufferedImage = new PolarMap(null).simplePolarProduct(PolarMap.buildPolarInfo(0, ProductType.VEL).backColor(ThematicMap.nullColor), product346.data, product346.azi);
        }

        if (type == ProductType.CAPPI) {
            // cappi 为三层径向数据
            for (int i = 0; i < 3; i++) {
                bufferedImage = new PolarMap(null).simplePolarProduct346(PolarMap.buildPolarInfo(0, null).backColor(ThematicMap.nullColor),
                        product346.data3d[i],
                        product346.azi, "R");
                writeImage(output, date, product346, project, bufferedImage, file.getName() + "_0" + i);
            }
            return;
        }

        if (type == ProductType.CS) {
            // 合成切变  单位 E-4/S
//            bufferedImage = new PolarMap(null).simplePolarProduct(PolarMap.buildPolarInfo(0, ProductType.CS).backColor(ThematicMap.nullColor), product346.data, product346.azi);
            bufferedImage = new PolarMap(null).simplePolarProduct346(PolarMap.buildPolarInfo(0, ProductType.CS).backColor(ThematicMap.nullColor), product346.data, product346.azi, "CS");
        }

        if (type == ProductType.EB) {
            bufferedImage = new PolarMap(null).simplePolarProduct346(PolarMap.buildPolarInfo(0, ProductType.ETB).backColor(ThematicMap.nullColor), product346.data, product346.azi, "EB");
            writeData(output, date, file.getName(), product346, product346.data, product346.azi, ProductType.EB);
        }
        if (type == ProductType.ET) {
            bufferedImage = new PolarMap(null).simplePolarProduct346(PolarMap.buildPolarInfo(0, ProductType.ETB).backColor(ThematicMap.nullColor), product346.data, product346.azi, "ET");
            writeData(output, date, file.getName(), product346, product346.data, product346.azi, ProductType.ET);
        }
        if (type == ProductType.SW) {
            bufferedImage = new PolarMap(null).simplePolarProduct346(PolarMap.buildPolarInfo(0, type).backColor(ThematicMap.nullColor), product346.data, product346.azi, "W");
            writeData(output, date, file.getName(), product346, product346.data, product346.azi, ProductType.SW);
        }
        if (type == ProductType.VEL) {
            bufferedImage = new PolarMap(null).simplePolarProduct346(PolarMap.buildPolarInfo(0, type).backColor(ThematicMap.nullColor), product346.data, product346.azi, "V");
            writeData(output, date, file.getName(), product346, product346.data, product346.azi, ProductType.VEL);
        }
        if (type == ProductType.REF) {
            bufferedImage = new PolarMap(null).simplePolarProduct346(PolarMap.buildPolarInfo(0, ProductType.REF).backColor(ThematicMap.nullColor), product346.data, product346.azi, "R");
            writeData(output, date, file.getName(), product346, product346.data, product346.azi, ProductType.REF);
        }
        if (type == ProductType.CR) {
            bufferedImage = new PolarMap(null).simplePolarProduct346(PolarMap.buildPolarInfo(0, ProductType.REF).backColor(ThematicMap.nullColor),
                    product346.data, product346.azi, "R");
            writeData(output, date, file.getName(), product346, product346.data, product346.azi, ProductType.REF);
        }

        // 栅格数据
        if (type == ProductType.VIL) {
            bufferedImage = rasterMap.drawSingleRaster(product346.data, "VIL", new Color(0, 0, 0, 0));
        }
        if (type == ProductType.OHP) {
            // 雨强 和 小时降水
            bufferedImage = rasterMap.drawSingleRaster(product346.data, "OHP", new Color(0, 0, 0, 0));
        }
        if (type == ProductType.RCS) {
            // 反射率垂直剖面
            bufferedImage = rasterMap.drawSingleRaster(product346.data, "R", new Color(0, 0, 0, 0));
//            bufferedImage = rasterMap.drawSingleRaster(product346.data, "R", new Color(0, 0, 0, 0));
        }
        if (type == ProductType.VCS) {
            // 速度垂直剖面
            bufferedImage = rasterMap.drawSingleRaster(product346.data, "V", new Color(0, 0, 0, 0));
        }
        if (type == ProductType.LRA || type == ProductType.LRM) {
            for (int i = 0; i < 3; i++) {
                bufferedImage = rasterMap.drawSingleRaster(product346.data3d[i], "R", new Color(0, 0, 0, 0));
//                bufferedImage = rasterMap.drawSingleRaster(product346.data3d[i], ProductType.REF, new Color(0, 0, 0, 0));
                writeImage(output, date, product346, project, bufferedImage, file.getName() + "_0" + i);
            }
            return;
        }

        if (type == ProductType.VWP || type == ProductType.VAD) {
            // 风廓线
            FileUtil.mkdir(output + date + File.separator);
            Map<Object, Object> map = new HashMap<>();
            map.put("BinLength", product346.BinLength);
            map.put("lon", product346.lon);
            map.put("lat", product346.lat);
            if (type == ProductType.VAD) {
                map.put("vad", product346.vad);
            } else {
                map.put("vwp", product346.vwp);
            }
            map.put("Bins", product346.Bins);
            map.put("MaxL", product346.MaxL);
            map.put("dateTime", DateUtil.format(product346.dateTime, DateConstants.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
            map.put("Records", product346.Records);
            FileUtil.writeUtf8String(new Gson().toJson(map), new File(output + date + File.separator + file.getName() + ".setting"));
            return;
        }

        if (bufferedImage != null) {
            writeImage(output, date, product346, project, bufferedImage, file.getName());
        }
    }

    public void writeData(String output, String date, String fname, Product382改 product346, double[][] data, double[] azi, ProductType productType) {
        FileUtil.mkdir(output + date + File.separator);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < azi.length; i++) {
            for (int j = 0; j < data[0].length; j++) {
                double d = data[i][j];
                if (d != GisConstants.UNDEF) {
                    if (productType == ProductType.ET || productType == ProductType.EB) {
                        d *= 100;
                    }
                    if (productType == ProductType.SW || productType == ProductType.VEL) {
                        d = (d - 129) * 0.5;
                    }
                    if (productType == ProductType.REF) {
                        d = (d - 66) * 0.5;
                    }
                }
                double angle = azi[i];
                double distance = j * product346.BinLength;
                PointD pointD = ForecastTask.computerThatLonLat(new PointD(product346.lon, product346.lat), angle, distance);
                list.add(pointD.X + "," + pointD.Y + "," + d);
            }
        }
        FileUtil.writeLines(list, new File(output + date + File.separator + fname + ".data"), Charset.defaultCharset());
    }

    public void writeImage(String output, String date, Product382改 product346, RadarGridData project, BufferedImage bufferedImage, String fname) throws IOException {
        FileUtil.mkdir(output + date + File.separator);
        Map map = new HashMap<>();
        map.put("BinLength", product346.BinLength);
        map.put("lon", product346.lon);
        map.put("lat", product346.lat);
        if (product346.Bins * product346.BinLength != 0) {
            map.put("extent", Common.getExtentRadius(product346.lon, product346.lat, product346.Bins * product346.BinLength));
            double res = product346.BinLength;
            if (product346.ele > 0){
                double ele = product346.ele;
                double distance = product346.Bins * product346.BinLength;
                distance = Math.cos(ele * Const.DEG2RAD) * distance;
                map.put("extent", Common.getExtentRadius(product346.lon, product346.lat, distance));
            }
        }
        map.put("Bins", product346.Bins);
        map.put("MaxL", product346.MaxL);
        map.put("dateTime", DateUtil.format(product346.dateTime, DateConstants.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        map.put("Records", product346.Records);
        FileUtil.writeUtf8String(new Gson().toJson(map), new File(output + date + File.separator + fname + ".setting"));
        ImageIO.write(bufferedImage, "png", new File(output + date + File.separator + fname + ".png"));


//        List<PointD> repoint = MathCommon.getDisPoint(points, lonlatPoints);
//        VCSData vcs = new VCSData();
//        int[] index = getElevationIndex(productType);
//        byte[][][] raw = this.getRaw(productType);
//        double[] ele = this.getElevation(productType);
//        double[][] azimuth = this.getAzimuth();
//        List<double[]> azis = new ArrayList<>();
//        List<byte[][]> raws = new ArrayList<>();
//        for (int i = 0; i < index.length; i++) {
//            RefObj<double[]> sortAzi = new RefObj<>(null);
//            RefObj<byte[][]> sortZ = new RefObj<>(null);
//            Cacl.sortAzi(azimuth[index[i]], raw[index[i]], sortAzi, sortZ);
//            azis.add(sortAzi.getValue());
//            raws.add(sortZ.getValue());
//        }
//        vcs.data = new double[altPoints][repoint.size()];
//        for (int i = 0; i < vcs.data.length; i++) {
//            double alt = maxAlt / altPoints * i;
//            alt /= (this.getResolution(productType) / 1000.0);
//            for (int j = 0; j < repoint.size(); j++) {
//                double angle = MathCommon.getAngleXY(repoint.get(j).Y, repoint.get(j).X, this.getRadarSite().getLat(), this.getRadarSite().getLon());
//                double distince = MathCommon.getDistanceKM(repoint.get(j).X, this.getRadarSite().getLon(), repoint.get(j).Y, this.getRadarSite().getLat());
//                distince /= (this.getResolution(productType) / 1000.0);
//                vcs.data[altPoints - 1 - i][j] = Cacl.bilinearInterpolat(angle, azis, ele, alt, distince, raws, productType);
//            }
//        }
//        vcs.setLonLat(repoint);
    }

    public static void main(String[] args) throws Exception {
        System.out.println("20240109090643000".length()
        );
        System.out.println();
//        CinradRadar cinradRadar = new CinradRadar();
//        cinradRadar.parse("Z:\\LD20220424200947744.VT382\\LD20130906150301453.VT346", CinradType.RADAR_382);
//        PolarMap polarMap = new PolarMap(cinradRadar.radar);
//        for (int i = 0; i < cinradRadar.radar.getElevation().length; i++) {
//            BufferedImage bufferedImage = new RasterMap(cinradRadar.radar).simplePPI(RasterMap.buildRasterInfo(ProductType.REF), i);
////            BufferedImage bufferedImage = polarMap.simplePolar(PolarMap.
////                    buildPolarInfo(i, ProductType.REF)
////                    .simpleDetail(true));
//            ImageIO.write(bufferedImage, "png", new File("D:\\test" + i + ".png"));
//        }
//        BufferedImage crimg = new RasterMap(cinradRadar.radar).simpleCR(RasterMap.buildRasterInfo(ProductType.CR));
//        ImageIO.write(crimg, "png", new File("D:\\cr.png"));
//        cinradRadar.radar.flush();
        Product382改 product346 = new Product382改();
        product346.parseProduct("D:\\work\\guorong\\国天资料\\20231111\\EB\\20231111_105757.00.007.005.S.bz2");
//        RadarGridData project = product346.project(ProductType.REF);

        RadarGridData project = product346.project(ProductType.REF);
        RasterMap rasterMap = new RasterMap(null);
//        BufferedImage bufferedImage = rasterMap.drawSingleGradientRaster(MathCommon.decode(project.radarData, ProductType.REF), ProductType.ET, new Color(0, 0, 0, 0));


        BufferedImage bufferedImage = rasterMap.drawSingleGradientRaster(MathCommon.decode(project.radarData, ProductType.REF), ProductType.ETB, new Color(0, 0, 0, 0));
        ImageIO.write(bufferedImage, "png", new File("D:\\work\\guorong\\国天资料\\20231111\\EB\\test.png"));
//        bufferedImage = rasterMap.drawSingleGradientRaster(MathCommon.decode(project.radarData,
//                ProductType.REF), ProductType.CR, new Color(0, 0, 0, 0));

    }

}
